<!-- 实习生证明模板新增、修改 -->
<template>
  <ContentCard>
    <template #header>
      <PageHeaderNew :title="title" :breadCrumb="breadCrumb" :showBack="true">
        <template #buts>
          <a-button type="primary" @click="save()">保存</a-button>
        </template>
      </PageHeaderNew>
    </template>
    <a-form
      ref="formRef"
      direction="vertical"
      :model="internshipTemplateDetail.info"
      :rules="rules"
      auto-label-width
    >
      <a-form-item field="name" label="模板名称">
        <a-input
          placeholder="模板名称"
          v-model="internshipTemplateDetail.info.name"
        />
      </a-form-item>
      <a-form-item field="explain" label="模板说明">
        <a-textarea
          placeholder="模板说明"
          v-model="internshipTemplateDetail.info.remark"
          :auto-size="{
            minRows: 3
          }"
          :max-length="300"
          show-word-limit
        />
      </a-form-item>
      <a-form-item field="direction" label="模板尺寸">
        <a-space direction="vertical" size="large">
          <a-radio-group
            :default-value="1"
            v-model="internshipTemplateDetail.info.direction"
          >
            <a-radio :value="1">A4 纵版</a-radio>
            <a-radio :value="2">A4 横版</a-radio>
          </a-radio-group>
        </a-space>
      </a-form-item>
      <a-form-item field="enable" label="是否启用">
        <a-switch
          :checked-value="1"
          :unchecked-value="2"
          v-model="internshipTemplateDetail.info.enable"
        />
      </a-form-item>
      <a-form-item field="approve" label="是否审批">
        <a-switch
          :checked-value="1"
          :unchecked-value="2"
          v-model="internshipTemplateDetail.info.approve"
        />
      </a-form-item>
      <a-form-item field="content" label="模板内容">
        <div class="content">
          <section class="control">
            <a-input-search
              v-model="searchVal"
              search-button
              @input="onSearch"
              @press-enter="onSearch"
              placeholder="快速搜索变量"
              class="input"
            ></a-input-search>
            <a-tabs :default-active-key="0">
              <a-tab-pane
                :key="index"
                :title="item.subDetail.cnName"
                v-for="(item, index) in currControlData"
              >
                <a-space wrap>
                  <a-button
                    v-for="(item2, index2) in item.subDetail.subRelDetail"
                    :key="item2.id"
                    @click="
                      inputLabel(
                        item2,
                        (() => {
                          let num = index2;
                          for (let i = 0; i < index2; i++) {
                            num +=
                              currControlData[i].subDetail.subRelDetail.length;
                          }
                          return num;
                        })()
                      )
                    "
                    >{{ item2.ctlCnName }}
                  </a-button>
                </a-space>
              </a-tab-pane>
            </a-tabs>
          </section>
          <section>
            <RichTextNew
              v-model:content="internshipTemplateDetail.info.text"
              :width="1000"
              ref="rich"
            ></RichTextNew>
          </section>
        </div>
      </a-form-item>
      <!-- <a-form-item field="file" label="附件">
        <a-button @click="upload()">上传文件</a-button>
      </a-form-item> -->
    </a-form>
  </ContentCard>
</template>
<script setup lang="ts">
import * as apiVariation from '@/apis/human/base/variationManager';
import { TEditInternshipTemplate } from '@/apis/human/base/variationManager/type';
import {
  PostInternshipProofTemplate,
  PutInternshipProofTemplate,
  CheckInternshipProofTemplate
} from '@/apis/management/human/baseSetting/certificateSetting';
import { GetBusinessModalData } from '@/apis/controltotal';
import { useRoute, useRouter } from 'vue-router';
import { Message } from '@arco-design/web-vue';
import RichTextCertificate from '@/components/RichTextCertificate/index.vue';
import { changeControlData } from '@/utils/control';
import { cloneDeep } from 'lodash';

const route = useRoute();
const router = useRouter();
let details = route.query;
let title = details.id ? '编辑开具离职证明模板' : '新增开具离职证明模板';
let breadCrumb: string[] = ['人事', '异动管理', `${title}`];
const formRef = ref();

let originControlData = ref([]), // 储存原始控件信息
  currControlData = ref<any>([]), // 储存当前控件信息
  searchVal = ref('');
const init = async () => {
  // 获取控件总集数据
  const { funcCtlInfos }: any = await GetBusinessModalData({
    funcCode: 'SER_FUNC9B158E4240DE49979E62895D0AEF9080'
  });

  controlList.value = changeControlData(funcCtlInfos, 'ctlDetail');
  originControlData.value = funcCtlInfos.children;
  currControlData.value = cloneDeep(funcCtlInfos.children);
  internshipTemplateDetail.info.id = route.query.id
    ? Number(route.query.id)
    : void 0;
  if (
    !internshipTemplateDetail.info.id &&
    internshipTemplateDetail.info.isCopy == 'false'
  )
    return;
  getData();
};
init();

// 搜索框
const onSearch = () => {
  currControlData.value = [];
  if (searchVal.value === '') {
    currControlData.value = cloneDeep(originControlData.value);
  } else {
    for (let item of originControlData.value) {
      item.subDetail.subRelDetail.forEach((item2: any) => {
        if (item2.ctlCnName.includes(searchVal.value)) {
          // 判断如果该控件所属的子集不存在，则创建一个子集，否则直接将控件信息赋值给subRelDetail
          if (
            currControlData.value[currControlData.value.length - 1]?.id !==
            item.id
          ) {
            currControlData.value.push({
              id: item.id,
              subDetail: {
                cnName: item.subDetail.cnName,
                subRelDetail: []
              }
            });
          }
          currControlData.value[
            currControlData.value.length - 1
          ].subDetail.subRelDetail.push(item2);
        }
      });
    }
  }
};

// 校验名称
const validateName = async (val: string, cb: any) => {
  try {
    if (
      internshipTemplateDetail.info.id &&
      internshipTemplateDetail.info.name === val
    ) {
      return;
    } else {
      const res = await CheckInternshipProofTemplate({
        name: val,
        type: 2
      });
      if (res.code) cb(`${res.msg}`);
    }
  } catch (error: unknown) {
    console.log(error);
  }
};
const rules = {
  name: [
    {
      required: true,
      message: '请填写名称',
      trigger: "['change', 'input', 'blur']"
    },
    {
      validator: validateName
    }
  ],
  direction: [
    {
      required: true,
      message: '请选择尺寸'
    }
  ]
};
let codes = ref<any[]>([]); // 储存当前选择的控件
const internshipTemplateDetail = reactive<{ info: any }>({
  info: {
    name: '', // 模板名称
    remark: '', // 模板描述
    required: 2, // 是否默认 1是 2否
    enable: 1, // 是否启用 1是 2否
    direction: 1, //默认1 模板页面方向 1：A4纵版 2：A4横版
    text: '', // 模板内容
    codes: '', // 控件编码数组，逗号隔开
    approve: 2,
    type: 2 // 离职默认传2
  }
});
// tab选项初始数据
const controlList: any = ref();
// 富文本ref
const rich = ref();
// 新增tab
const inputLabel = (item: any, ind: number) => {
  if (codes.value.length !== 0) {
    if (
      !codes.value.some((ele: any) => ele === controlList.value[ind].ctlCode)
    ) {
      codes.value.push(controlList.value[ind].ctlCode);
    }
  } else {
    codes.value.push(controlList.value[ind].ctlCode);
  }

  const tag = `&nbsp;<span style="text-decoration: underline; color: #3598db; font-size: 12pt;">#${item.ctlCnName}#</span>&nbsp;`;
  nextTick(() => {
    rich.value.insertContent(tag);
  });
};

// 编辑情况下需要转换成数字类型的属性
const NumberTypeEnum = [
  'id',
  'required',
  'direction',
  'isShowDefault',
  'enable',
  'type',
  'approve'
];
//获取实习证明模板详情

const getData = async () => {
  internshipTemplateDetail.info = {
    ...details
  };
  codes.value = [];
  const currCodes = internshipTemplateDetail.info.codes.split(',');

  for (let i in internshipTemplateDetail.info) {
    if (NumberTypeEnum.includes(i))
      internshipTemplateDetail.info[i] = +internshipTemplateDetail.info[i];
  }
  controlList.value.forEach((item: any) => {
    let regexp = new RegExp(`#${item.ctlCode}#`, 'g');
    internshipTemplateDetail.info.text =
      internshipTemplateDetail.info.text.replace(regexp, `#${item.cnName}#`);
    if (currCodes.includes(item.ctlCode)) codes.value.push(item.ctlCode);
  });
};

const save = async () => {
  // 验证表单
  if (await formRef.value.validate()) return;
  let {
    info: { id }
  } = internshipTemplateDetail;
  let msg = '新增成功';
  // 新增
  if (!id) {
    controlList.value.forEach((item: any) => {
      let regexp = new RegExp(`#${item.ctlCnName}#`, 'g');
      // currTemplate.value = currTemplate.value.replace(regexp, `#${item.cnName}#`);
      internshipTemplateDetail.info.text =
        internshipTemplateDetail.info.text.replace(regexp, `#${item.ctlCode}#`);
    });
    internshipTemplateDetail.info.codes = codes.value.join(',');
    internshipTemplateDetail.info.type = 2;

    await PostInternshipProofTemplate(internshipTemplateDetail.info);
  } else {
    // 编辑
    controlList.value.forEach((item: any) => {
      let regexp = new RegExp(`#${item.ctlCnName}#`, 'g');
      // currTemplate.value = currTemplate.value.replace(regexp, `#${item.cnName}#`);
      internshipTemplateDetail.info.text =
        internshipTemplateDetail.info.text.replace(regexp, `#${item.ctlCode}#`);
    });
    internshipTemplateDetail.info.codes = codes.value.join(',');

    await PutInternshipProofTemplate(internshipTemplateDetail.info);

    msg = '编辑成功';
  }
  Message.success(msg);
  router.back();
};
const upload = () => {
  Message.warning('敬请期待~');
};
</script>
<style lang="less" scoped>
.index {
  padding: 10px 20px;

  .content {
    width: 100%;
    // display: grid;
    // grid-template-columns: 3fr 1fr;
    .control {
      .input {
        margin-bottom: 20px;
        width: 350px;
      }
    }
  }
}
</style>
